﻿using qcloudsms_csharp;
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Text.RegularExpressions;

namespace XieCan.AspMVC.References.Tencent
{
    /// <summary>
    /// 腾讯短信API功能封装
    /// </summary>
    public class TencentSMSHelper
    {
        #region 公共配置

        private static NameValueCollection Configuration => ConfigurationManager.AppSettings;

        /// <summary>
        /// 手机号验证表达式
        /// </summary>
        private static Regex MobileRegex
        {
            get
            {
                var regex = Configuration["MobileValidate"];
                if (string.IsNullOrWhiteSpace(regex))
                    regex = @"^1[3456789]\d{9}$";
                return new Regex(regex);
            }
        }

        /// <summary>
        /// 应用唯一标识
        /// </summary>
        private static int AppId
        {
            get
            {
                var appId = Configuration["TencentSMS:AppId"];
                if (string.IsNullOrWhiteSpace(appId))
                    return 0;

                if (int.TryParse(appId, out int res))
                {
                    return res;
                }
                return 0;
            }
        }

        /// <summary>
        /// 应用授权密钥
        /// </summary>
        private static string AppKey
        {
            get
            {
                var appKey = Configuration["TencentSMS:AppKey"];
                return string.IsNullOrWhiteSpace(appKey) ? "" : appKey;
            }
        }

        #endregion

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phoneNumber">要发送到的手机号码</param>
        /// <param name="templateId">短信模板Id</param>
        /// <param name="parameters">短信模板传值</param>
        /// <param name="nationCode">国家代码</param>
        /// <returns></returns>
        public static OperateResult<bool> SendSMS(string phoneNumber, int templateId, string nationCode = "86", string sign = "", string extent = "", string ext = "", params string[] parameters)
        {
            // 手机号有效性
            if (string.IsNullOrWhiteSpace(phoneNumber) || !MobileRegex.IsMatch(phoneNumber))
            {
                return OperateResult<bool>.Failed("无效的手机号码！");
            }
            // 获取API参数
            SmsSingleSender smsSender = new SmsSingleSender(AppId, AppKey);
            SmsSingleSenderResult smsResult;
            try
            {
                smsResult = smsSender.sendWithParam(nationCode, phoneNumber, templateId, parameters, sign, extent, ext);
            }
            catch (Exception ex)
            {
                return OperateResult<bool>.Failed(ex);
            }

            if (smsResult.result == 0)
            {
                return OperateResult<bool>.Succeeded(true);
            }
            else
            {
                return OperateResult<bool>.Failed(smsResult.errMsg);
            }
        }
    }
}